<?php

namespace Services\User;

use Common\Model\User\UserViewLogModel;
use Common\Model\User\UserVipLogModel;
use Common\Model\UserCardListModel;
use Common\Model\UserModel;
use Services\BaseService;
use Services\Log\LogService;
use Services\User\Exceptions\UserException;

class UserService extends BaseService
{
    /** @var UserModel $model */
    private $model;

    public function __construct()
    {
        $this->model = new UserModel();
    }

    /**
     * 通过用户id获取用户信息
     * @param $userId
     * @return array|false|mixed|string
     */
    public function getUserById($userId)
    {
        if (!$userInfo = $this->model->where(['id' => $userId])->find()) {
            return false;
        }
        $userInfo['user_headimg'] = $userInfo['user_headimg'] ? $userInfo['user_headimg'] : "http://xcx.tfxiaochengxu.com/2018-06-15_5b235fa500726.png";
        if (!empty($field)) {
            return $userInfo[$field] ? $userInfo[$field] : '';
        }
        return $userInfo ? $userInfo : false;
    }

    /**
     * 更新用户的下次提醒时间
     * @param $userId
     * @return void
     */
    public function updateUserMessageTip($userId)
    {
        try {
            $userInfo = $this->getUserById($userId);
            if (!$userInfo) {
                throw new UserException('未找到用户');
            }
            $userViewLog = new UserViewLogModel();
            $userViewLog->where(['view_user_id' => $userId])->save([
                'is_tip' => 1,
                'tip_time' => get_now_date(),
            ]);

            //判断用户需要多久提醒一次
            $viewLogTipType = $userInfo['view_log_tip_type'];
            $saveData = ['log_tip_time' => 0];
            if ($viewLogTipType == UserModel::TIP_TYPE_15_MINUTE) {
                $saveData['log_tip_time'] = strtotime("+15 minutes", time());
            } elseif ($viewLogTipType == UserModel::TIP_TYPE_ONE_HOUR) {
                $saveData['log_tip_time'] = strtotime('+1 hour', time());
            } elseif ($viewLogTipType == UserModel::TIP_TYPE_3_HOUR) {
                $saveData['log_tip_time'] = strtotime('+3 hour', time());
            }
            (new UserModel())->where('id', $userId)->save($saveData);
        } catch (\Exception $e) {
            LogService::write('更新用户下次提醒时间失败', $e->getMessage());
        }
        return true;
    }

    /**
     * 获取用户的名片数据
     * @param $userId
     * @return array|false|mixed|string
     */
    public function card($userId)
    {
        $card_m = new UserCardListModel();
        $cardInfo = $card_m->getInfo(['user_id' => $userId]);
        return $cardInfo ? $cardInfo : false;
    }

    /**
     * 开通vip
     * @param $userId :用户id
     * @param $vipDayNumber :天数
     * @param $channel :渠道
     * @return boolean
     */
    public function openVip($userId, $vipDayNumber, $channel)
    {
        $result = false;
        M()->startTrans();
        try {
            $vipDayNumber = (int)$vipDayNumber;
            $userInfo = $this->getUserById($userId);
            if (!$userInfo) {
                throw new UserException('未找到用户');
            }
            $vipExpiredAt = strtotime($userInfo['vip_expired_at']);
            $endTime = '';
            if ($userInfo['is_vip'] && $vipExpiredAt > time()) {
                $endTime = strtodate($vipExpiredAt + 3600 * 24 * $vipDayNumber);
            } else {
                $endTime = strtodate(time() + 3600 * 24 * $vipDayNumber);
            }
            if (!$userInfo['is_vip'] || !$vipExpiredAt) {
                $endTime = strtodate(time() + 3600 * 24 * $vipDayNumber);
            }
            $log = [
                'user_id' => $userId,
                'channel' => $channel,
                'update_vip_end_time' => $endTime,
                'created_at' => get_now_date(),
                'updated_at' => get_now_date(),
            ];
            $addLog = (new UserVipLogModel())->add($log);
            $saveUser = (new UserModel())->where(['id' => $userId])->save([
                'is_vip' => UserModel::IS_VIP,
                'vip_expired_at' => $endTime,
            ]);

            if ($addLog && $saveUser) {
                M()->commit();
                $result = true;
            } else {
                M()->rollback();
            }
        } catch (\Exception $e) {
            M()->rollback();
            LogService::writeWithDb(format_exception($e), $userId . '_开通vip失败', 'vip');
        }
        return $result;
    }

    /**
     * 判度用户是否为意向客户
     * @param $userId
     * @param $viewUserId
     * @return bool
     */
    public function judgeUserIsPotentialCustomer($userId, $viewUserId)
    {
        $markerNumber = 3;
        $sql = <<<SQL
SELECT
	* 
FROM
	( SELECT count( * ) AS view_count FROM user_view_log WHERE user_id = %d AND view_user_id = %d AND type = 'article' GROUP BY model_id ) AS article_view_count 
WHERE
	view_count >= %d
SQL;
        $result = M()->query(sprintf($sql, $userId, $viewUserId, $markerNumber));

        return !empty($result);
    }
}
